//
//  HPWellcomeView.swift
//  MyWeibo
//
//  Created by apple on 16/4/12.
//  Copyright © 2016年 Apengpeng. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

class HPWellcomeView: UIViewController {
    
    // 在loadview中加载
    override func loadView() {
        view = UIImageView(image: UIImage(named: "ad_background"))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置界面
        setupUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)
        startAnimation()
    }
    
    // 设置界面中子控件
    func setupUI() {
        
        view.addSubview(iconImageView)
        view.addSubview(nameLabel)
        
        // 裁剪用户头像
        iconImageView.cornerRadious = 45
        // 添加约束
        iconImageView.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom).offset(-180)
            make.centerX.equalTo(self.view.snp_centerX)
            make.size.equalTo(CGSize(width: 90, height: 90))
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(iconImageView.snp_centerX)
            make.top.equalTo(iconImageView.snp_bottom).offset(16)
        }
        
        // 请求头像图片
        iconImageView.sd_setImageWithURL(HPUserAccountViewModel.sharedUserAccountViewModel.iconImageURL)
    }
    
    
    // 添加动画
    func startAnimation(){
        
        let offset = -screenHeight + 180
        nameLabel.alpha = 0
        self.iconImageView.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(self.view.snp_bottom).offset(offset)
        }
        
        // 强制刷新页面
        UIView.animateWithDuration(1.8, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 6.0, options: [], animations: { () -> Void in
            self.view.layoutIfNeeded()
            }) { (_) -> Void in
                
                // 给label添加动画
                UIView.animateWithDuration(1.0, animations: { () -> Void in
                    
                    // 设置label的aphla
                    self.nameLabel.alpha = 1.0
                    }, completion: { (_) -> Void in
//                        UIApplication.sharedApplication().keyWindow?.rootViewController = HPMainViewController()
                        //使用通知跳转到登陆页面, object 表示接收通知的对象,
                        NSNotificationCenter.defaultCenter().postNotificationName(HPSwitchRootViewController, object: "MainVc")
                })
        }
        
    }
    
    // 赖加载控件
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))
    
    private lazy var nameLabel = UILabel(text: HPUserAccountViewModel.sharedUserAccountViewModel.userAccount?.name ?? "", textColor: UIColor.darkTextColor(), fontSzie: 16, margin: 0)
}
